<?php
declare (strict_types = 1);
namespace app\index\model\user;

use think\facade\Cache;
use think\facade\Db;
use think\Model;

/**
 * @mixin \think\Model
 */
class User extends Model
{
    protected $pk = "id";

    /**
     * 用户注册
     * @param $data
     * @return bool|int|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function registerUser($data){
        if(isset($data['nickname']) && $data['nickname']){
            $nickName = $data['nickname'];
        }else{
            $nickName = substr($data['phone'], 0, 3) . '****' . substr($data['phone'], 7, 4);
        }
        $useData = [
            'account' => $data['phone'],
            'log_pwd' => isset($data['pwd']) ? password_hash($data['pwd'], PASSWORD_BCRYPT) : '',
            'nickname' => $nickName,
            'avatar' => isset($data['avatar']) ? $data['avatar'] : '',
            'phone' => $data['phone'],
            'pwd' => '',
            'last_ip' => app('request')->ip(),
            'spread_uid' => isset($data['spread']) ? $data['spread']:0,
            'spread_time' => date("Y-m-d H:i:s"),
            'user_type' => $data['user_type'],
            'create_time'=>date("Y-m-d H:i:s"),
        ];
        //添加用户信息
        Db::startTrans();
        $userResult = $this->insertGetId($useData);
        if($userResult){
            $userCardModel = new UserCard();
            $cardResult = $userCardModel->addUserCard($userResult,$useData);
            if($cardResult){
                Db::commit();
                return $userResult;
            }else{
                Db::rollback();
                return false;
            }
        }else{
            Db::rollback();
            return false;
        }

    }

    /**
     * 获取用户信息
     * @param $id
     * @param $addWhere
     * @return array|null|Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function getUserInfoById($id,$addWhere = []){
        return $this->where('id',$id)->where($addWhere)->find();
    }

    /**
     * 获取用户信息
     * @param $id
     * @param $addWhere
     * @return array|null|Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function UserInfoById($id,$field="*"){
        return $this->where('id',$id)->field($field)->find();
    }


    /**
     * @param string $token
     * @author xaboy
     * @day 2020-04-29
     */
    public function clearToken(string $token)
    {
        Cache::delete('user_' . $token);
    }

    /**
     * 获取用户
     * @param $account
     * @return array|null|Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function getUserByAccount($account){
        return $this->where('account',$account)->find();
    }

    /**
     * 修改用户信息
     * @param $userId
     * @param $data
     * @return static
     */
    function updateUserInfo($userId,$data){
        return $this->where('id',$userId)->update($data);
    }

    /**
     * 绑定用户信息
     * @param $data
     * @param $wechatUser
     * @return bool|Model|static
     * @throws \think\db\exception\DbException
     */
    public function bindWechatUser($data,$wechatUser)
    {
        $user =$this->getUserByAccount($data['phone']);
        $request = request();
        if ($user) {
            $user->save(array_filter([
                'last_time' => date('Y-m-d H:i:s'),
                'last_ip' => $request->ip(),
            ]));
            $bindResult = Db::name('wechat_user')->where('wechat_user_id',$wechatUser['wechat_user_id'])->update(['user_id'=>$user['id']]);
        } else {
            $userId = $this->registerUser([
                'account' => $data['phone'],
                'pwd' => 'qyhs123456',
                'nickname' => $wechatUser['nickname'] ?? '',
                'avatar' => $wechatUser['headimgurl'] ?? '',
                'phone' => $data['phone'],
                'spread' => 0,
                'user_type' => 'wechat',
            ]);
            if($userId){
                $user = $this->getUserInfoById($userId);
                $bindResult = Db::name('wechat_user')->where('wechat_user_id',$wechatUser['wechat_user_id'])->update(['user_id'=>$user['id']]);
            }else{
                return false;
            }
        }
        if($bindResult){
            if(!is_array($user)) $user = $user->toArray();
            return $user;
        }else{
            return false;
        }
    }

}
